//
//  HeaderView.m
//  Travelmemory
//
//  Created by lanou3g on 16/3/31.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "HeaderView.h"


@interface HeaderView()

@property (nonatomic, strong) NSMutableArray *blurImages;
@property (nonatomic, assign) CGFloat OTCoverHeight;

@end

@implementation HeaderView

- (HeaderView *)initWitTableViewWithHeaderImage:(UIImage *)headerImage withheaderImageHight:(CGFloat)headerImageHeight {
    
    CGRect bounds = [[UIScreen mainScreen] bounds];
    self = [[HeaderView alloc] initWithFrame:bounds];
    
    self.headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, headerImageHeight)];
    [self.headerImageView setImage:headerImage];
    [self addSubview:self.headerImageView];
    
    self.OTCoverHeight = headerImageHeight;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.frame style:UITableViewStylePlain];
    self.tableView.tableHeaderView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, headerImageHeight)];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.tableView];
    
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    
    self.blurImages = [[NSMutableArray alloc] init];
    [self prepareForBlurImages];
    return self;
    
}

- (void)setHeaderImage:(UIImage *)headerImage{
    [self.headerImageView setImage:headerImage];
    [self.blurImages removeAllObjects];
    [self prepareForBlurImages];
}

- (void)prepareForBlurImages
{
    
    [self.blurImages addObject:self.headerImageView.image];
    for (NSUInteger i = 0; i < self.OTCoverHeight/10; i++) {
        [self.blurImages addObject:self.headerImageView.image];
    }
}
- (void)animationForTableView{
    CGFloat offset = self.tableView.contentOffset.y;
    
    if (self.tableView.contentOffset.y > 0) {
        
        NSInteger index = offset / 10;
        if (index < 0) {
            index = 0;
        }
        else if(index >= self.blurImages.count) {
            index = self.blurImages.count - 1;
        }
        UIImage *image = self.blurImages[index];
        if (self.headerImageView.image != image) {
            [self.headerImageView setImage:image];
            
        }
        self.tableView.backgroundColor = [UIColor clearColor];
        
    }
    else {
        self.headerImageView.frame = CGRectMake(offset,0, self.frame.size.width + (-offset) * 2, self.OTCoverHeight + (-offset));
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (self.tableView) {
        [self animationForTableView];
    }
}

//  减少内存
- (void)dealloc
{
    if (self.tableView) {
        
        [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    }
    
}


@end
